package com.masterviame.Authc.service.Impl;

import com.masterviame.Authc.pojo.Role;
import com.masterviame.Authc.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by mastervictory on 2017/12/14.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.DEFAULT,
timeout = 20)
public class RoleServiceImpl  implements RoleService{

    @Autowired
    private RoleService roleService;
    @Override
    public void createRole(Role role) {
        if (role!=null)
            roleService.createRole(role);
    }

    @Override
    public void stopRole(long roleid) {
        Role role=roleService.getRoleByid(roleid);
        if (role!=null)
        {
            role.setAvailable(false);
            roleService.updateRole(role);
        }
    }

    @Override
    public void correlationPermissions(long roleid, long... permissions) {
        Role role=roleService.getRoleByid(roleid);
        String permissionsCode=role.getPermissionsCode();
        for (long pid:permissions){
            permissionsCode+=(","+pid);
        }
        role.setPermissionsCode(permissionsCode);
        roleService.updateRole(role);
    }

    @Override
    public void uncorrelationPermissions(long roleid, long... permissions) {
        Role role=roleService.getRoleByid(roleid);
        String permisssionCode=role.getPermissionsCode();
        for (long pid:permissions){
            permisssionCode.replace(pid+",","");
        }
        role.setPermissionsCode(permisssionCode);
        roleService.updateRole(role);
    }

    @Override
    public List<Role> getRoles() {
        List<Role> roleList=roleService.getRoles();
        if (roleList!=null)
            return roleList;
        throw new NullPointerException("permissionList is null");
    }

    @Override
    public void deleteRoles(long roleid) {
        roleService.deleteRoles(roleid);
    }

    @Override
    public Role getRoleByid(long roleid) {
        Role role=roleService.getRoleByid(roleid);
        if (role!=null)
            return role;
        throw new NullPointerException("get value role is null");
    }

    @Override
    public Role updateRole(Role role) {
        if (role!=null)
            roleService.updateRole(role);
        throw new NullPointerException("role is null");
    }
}
